package com.qyhl.webtv.module_circle.circle.party;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.mobstat.StatService;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.SingleChoiceDialog;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.circle.CircleHomeBean;
import com.qyhl.webtv.commonlib.entity.intergral.CoinBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.editbar.EditBar;
import com.qyhl.webtv.commonlib.utils.view.editbar.EditBarOnClickListenerImpl;
import com.qyhl.webtv.module_circle.R;
import com.qyhl.webtv.module_circle.R2;
import com.qyhl.webtv.module_circle.circle.topicdetail.TopicDetailContract;
import com.qyhl.webtv.module_circle.circle.topicdetail.TopicDetailPresenter;
import com.qyhl.webtv.module_circle.utils.itemview.ItemPictureView;
import com.qyhl.webtv.module_circle.utils.itemview.ItemTextView;
import com.qyhl.webtv.module_circle.utils.itemview.ItemVideoView;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.umeng.analytics.MobclickAgent;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.wrapper.EmptyWrapper;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class PartyCircleFragment extends BaseFragment implements TopicDetailContract.TopicDetailView {
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.editBar)
    EditBar editBar;

    private TopicDetailPresenter mPresenter;

    private String lastId = "0";

    private MultiItemTypeAdapter<CircleHomeBean> mAdapter;

    private List<CircleHomeBean> mDataList;

    private boolean editBarEnable = true;

    private CircleHomeBean mBean;
    private int position, uPos;
    private String date, content;

    private EmptyWrapper emptyWrapper;

    private String circleId;

    public void setCircleId(String circleId) {
        this.circleId = circleId;
    }

    public static PartyCircleFragment newInstance(String circleId) {
        PartyCircleFragment fragment = new PartyCircleFragment();
        fragment.setCircleId(circleId);
        return fragment;
    }


    @Override
    public void initImmersionBar() {
        ImmersionBar.with(this)
                .statusBarDarkFont(true)
                .fitsSystemWindows(true)
                .init();
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.circle_fragment_party_circle, null);
    }

    @Override
    protected void create() {
        loadMask.setStatus(LoadingLayout.Loading);

        BusFactory.getBus().register(this);
        mPresenter = new TopicDetailPresenter(this);


        editBar.hideShare(true);
        editBar.hideComment(true);
        editBar.hideCollect(true);
        mDataList = new ArrayList<>();

        refresh.setRefreshHeader(new MaterialHeader(getContext()));
        refresh.setRefreshFooter(new ClassicsFooter(getContext()));
        refresh.setEnableLoadMore(true);

        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycleView.setLayoutManager(linearLayoutManager);

        //添加自定义分割线
        DividerItemDecoration divider = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(getContext(), R.drawable.circle_recycleview_divider));
        recycleView.addItemDecoration(divider);


        mAdapter = new MultiItemTypeAdapter<CircleHomeBean>(getContext(), mDataList);
        mAdapter.addItemViewDelegate(new ItemPictureView(getActivity(), true, true));
        mAdapter.addItemViewDelegate(new ItemTextView(getActivity(), true, true));
        mAdapter.addItemViewDelegate(new ItemVideoView(getActivity(), true, true));

        emptyWrapper = new EmptyWrapper(mAdapter);
        emptyWrapper.setEmptyView(R.layout.circle_layout_circle_content_emptyview);
        recycleView.setAdapter(emptyWrapper);

        mPresenter.getDatas(circleId, lastId);
    }

    @Override
    protected void setListener() {
        //重载
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                lastId = "0";
                mPresenter.getDatas(circleId, lastId);
            }
        });

        //刷新
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                lastId = "0";
                mPresenter.getDatas(circleId, lastId);
            }
        });

        //加载更多
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                mPresenter.getDatas(circleId, lastId);
            }
        });

        //item点击跳转
        mAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {

                Bundle bundle = new Bundle();
                bundle.putString("id", mDataList.get(position).getId() + "");
                RouterManager.router(ARouterPathConstant.CIRCLE_DETAIL, bundle);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        editBar.setEditBarOnClickListener(new EditBarOnClickListenerImpl() {
            @Override
            public void onSend() {
                if (editBarEnable) {
                    editBarEnable = false;

                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                        @Override
                        public void login(boolean isLogin) {
                            if (isLogin) {
                                content = editBar.getContent();
                                String dstUsername;
                                if (StringUtils.isNotEmpty(content)) {
                                    if (uPos == -1) {
                                        dstUsername = "";
                                    } else {
                                        dstUsername = mBean.getPostList().get(uPos).getUser().getUsername();
                                    }
                                    date = DateUtils.getCurrentTime();
                                    mPresenter.sendComment(mBean.getId() + "", content, dstUsername);
                                    editBar.clearContent();
                                } else {
                                    showToast("评论不能为空！");
                                    editBarEnable = true;
                                }
                            } else {
                                showToast("尚未登录或登录已失效！");
                                RouterManager.routerLogin(getContext(), 0);
                                editBarEnable = true;
                            }
                        }

                        @Override
                        public void error(String s) {

                        }
                    });

                }

            }
        });

        recycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (RecyclerView.SCROLL_STATE_DRAGGING == newState && editBar.getVisibility() == View.VISIBLE) {
                    editBar.clearContent();
                    editBar.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {
        GSYVideoManager.onResume();
    }

    @Override
    protected void onHide() {
        GSYVideoManager.onPause();
    }

    @Override
    public void setDatas(List<CircleHomeBean> beanList, boolean isMore) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~~");

        if (beanList != null && beanList.size() > 0) {
            lastId = beanList.get(beanList.size() - 1).getId() + "";
        }

        if (isMore) {
            refresh.finishLoadMore();
            mDataList.addAll(beanList);
        } else {
            refresh.setEnableLoadMore(beanList != null && beanList.size() > 0);
            refresh.finishRefresh();
            mDataList.clear();
            mDataList.addAll(beanList);
        }

        emptyWrapper.notifyDataSetChanged();
    }

    @Override
    public void setBase(CircleHomeBean.TagList bean) {

    }

    @Override
    public void setNetError(String msg) {
        refresh.finishRefresh();
        refresh.finishLoadMore();
        loadMask.setStatus(LoadingLayout.No_Network);
        loadMask.setReloadButtonText("点击重试~~");
        loadMask.setNoNetworkText(msg);
    }

    @Override
    public void setError(String msg) {
        refresh.finishRefresh();
        refresh.finishLoadMore();
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~~");
        loadMask.setErrorText(msg);
    }

    @Override
    public void setEmpty(String msg) {
        refresh.finishRefresh();
        refresh.finishLoadMore();
        loadMask.setStatus(LoadingLayout.Empty);
        loadMask.setReloadButtonText("点击重试~~");
        loadMask.setEmptyText(msg);
    }

    @Override
    public void setLog(String msg) {
        refresh.finishLoadMore();
        Log.i("info", msg);
    }

    @Override
    public void showMessage(String msg) {
        refresh.finishLoadMore();
        showToast(msg);
    }

    @Override
    public void setBaseError(String msg) {
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setErrorText(msg);
        loadMask.setReloadButtonText("点击重试~~");
    }

    @Override
    public void commentSuccess(int postId, String msg, int code) {
        showToast(msg);

        //0评论  1回复
        CircleHomeBean.PostList postBean;
        String nickName = CommonUtils.getInstance().getNickName();
        String userName = CommonUtils.getInstance().getUserName();
        String headicon = CommonUtils.getInstance().getUserLogo();
        if (code == 0) {
            postBean = new CircleHomeBean.PostList(date, postId, 1, content, new CircleHomeBean.User(nickName, headicon, userName, false), mBean.getUser());
        } else {
            postBean = new CircleHomeBean.PostList(date, postId, 2, content, new CircleHomeBean.User(nickName, headicon, userName, false), mBean.getPostList().get(uPos).getUser());
        }
        if (mBean.getPostList() != null && mBean.getPostList().size() >= 4) {
            mBean.getPostList().add(0, postBean);
            mBean.getPostList().remove(3);
        } else if (mBean.getPostList() == null) {
            List<CircleHomeBean.PostList> beanList = new ArrayList<>();
            beanList.add(postBean);
            mBean.setPostList(beanList);
        } else {
            mBean.getPostList().add(0, postBean);
        }
        mBean.setPostCount(mBean.getPostCount() + 1);
        mDataList.set(position, mBean);
        emptyWrapper.notifyDataSetChanged();
        editBar.clearContent();
        editBar.setVisibility(View.GONE);
        editBarEnable = true;
    }

    @Override
    public void commentError(String msg) {
        editBarEnable = true;
        showToast(msg);
    }

    @Override
    public void getCoinError(String msg) {

    }

    @Override
    public void getCoinSuccess(CoinBean coinBean) {

    }

    /**
     * 评论事件
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void commentMessage(Event.CommentEvent event) {
        if (event != null) {
            mBean = event.getBean();
            position = event.getPostion();
            uPos = event.getuPos();
            editBar.setVisibility(View.VISIBLE);
            editBar.changeStateSend(getActivity());
            if (uPos < 0) {
                editBar.setEditTextHint("评论");
            } else {
                editBar.setEditTextHint("回复:" + mBean.getPostList().get(uPos).getUser().getNickName());
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void praiseMessage(Event.praiseRefreshEvent event) {
        if (event != null) {
            int topicId = event.getTopicId();
            for (int i = 0; i < mDataList.size(); i++) {
                if (mDataList.get(i).getId() == topicId) {
                    if (event.getType() == 1) {
                        mDataList.get(i).setLove(true);
                        mDataList.get(i).setLoveCount(mDataList.get(i).getLoveCount() + 1);
                    } else {
                        mDataList.get(i).setLove(false);
                        mDataList.get(i).setLoveCount(mDataList.get(i).getLoveCount() - 1);
                    }
                }
            }
            emptyWrapper.notifyDataSetChanged();
        }
    }

    /**
     * 登录状态改变事件
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(Event.LoginMessage event) {
        if (event != null) {
            mPresenter.getBaseInfo(circleId);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refresh(Event.circleRefresh event) {
        if (event != null && mDataList != null) {
            for (int i = 0; i < mDataList.size(); i++) {
                if (mDataList.get(i).getId() == event.getTopicId()) {
                    mDataList.remove(i);
                    mAdapter.notifyDataSetChanged();
                }
            }
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        //baidu
        StatService.onResume(getActivity());
        StatService.onPageStart(getContext(), "圈子话题");
        //umeng
        MobclickAgent.onPageStart("圈子话题");
        MobclickAgent.onResume(getContext());
        GSYVideoManager.onResume();
        ActionLogUtils.getInstance().onResume(getActivity(), ActionConstant.CIRCLETOPIC);
    }

    @Override
    public void onPause() {
        super.onPause();
        //baidu
        StatService.onPause(getActivity());
        StatService.onPageEnd(getContext(), "圈子话题");
        //umeng
        MobclickAgent.onPageEnd("圈子话题");
        MobclickAgent.onPause(getContext());
        GSYVideoManager.onPause();
        ActionLogUtils.getInstance().onPause(getActivity(), ActionConstant.CIRCLETOPIC);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        BusFactory.getBus().unregister(this);
        GSYVideoManager.releaseAllVideos();
    }


    @OnClick(R2.id.publish_btn)
    public void onClick() {
        new SingleChoiceDialog.Builder(getContext()).setTitle("类型", R.color.global_gray_lv2)
                .addList(new String[]{"图文", "视频"})
                .setCancelTextColor(R.color.global_base)
                .setOnItemClickListener(new SingleChoiceDialog.OnItemClickListener() {
                    @Override
                    public void OnItemClick(String title, int position) {
                        Bundle bundle = new Bundle();
                        bundle.putString("id", circleId);
                        switch (position) {
                            case 0:
                                bundle.putInt("type", 5);
                                break;
                            case 1:
                                bundle.putInt("type", 6);
                                break;
                            default:
                                break;
                        }
                        RouterManager.router(ARouterPathConstant.CIRCLE_ADD, bundle);
                    }
                })
                .show();
    }
}
